﻿using System;
using System.IO;
using System.Windows.Forms;

namespace MyVocabulary.Popup
{
    public partial class AddNewFolder : Form
    {
        #region Const

        protected static class FormMessages
        {
            public const string InvalidNameErrorMsg = "Please enter a valid name";
            public const string DuplicateNameErrorMsg = "A folder with this name already exists";
            public const string GeneralErrorMsg = "Error creating folder";
        }

        #endregion

        protected string parentFolder;

        public DirectoryInfo CreatedFolder;
        public event EventHandler OnNewFolderCreated;

        public AddNewFolder(string parentFolder)
        {
            this.parentFolder = parentFolder;
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {            
            if(tbName.Text.Length == 0)
            {
                lbError.Text = FormMessages.InvalidNameErrorMsg;
                toolTip1.SetToolTip(lbError, FormMessages.InvalidNameErrorMsg);
                return;                
            }

            try
            {
                var dir = new DirectoryInfo(parentFolder);
                //check if the directory already exists
                foreach (var directory in dir.GetDirectories())
                {
                    if(string.Compare(directory.Name,tbName.Text,true) == 0)
                    {
                        lbError.Text = FormMessages.DuplicateNameErrorMsg;
                        toolTip1.SetToolTip(lbError, FormMessages.DuplicateNameErrorMsg);
                        return;
                    }
                }

                //create the directory
                CreatedFolder = dir.CreateSubdirectory(tbName.Text);
                if (OnNewFolderCreated != null)
                    OnNewFolderCreated(this, null);
                Close();
            }
            catch (Exception exp)
            {
                lbError.Text = FormMessages.GeneralErrorMsg;
                toolTip1.SetToolTip(lbError,exp.Message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}